from channels.generic.websocket import WebsocketConsumer
from asgiref.sync import async_to_sync


# connected_clients = {}

class ChatConsumers(WebsocketConsumer):
    def connect(self):
        async_to_sync(self.channel_layer.group_add)("flood_group", self.channel_name)

        self.accept()
        self.send("Connected!")
        # print(self.channel_name)    # specific..inmemory!HKVPRFVXLpWl
        # connected_clients[self.channel_name] = 1

    def receive(self, text_data=None, bytes_data=None):
        async_to_sync(self.channel_layer.group_send)(
            "flood_group",
            {
                "type": "flood_message",
                "message": text_data
            }
        )

    def flood_message(self, event):
        self.send(text_data=event['message'])

    def disconnect(self, code):
        async_to_sync(self.channel_layer.group_discard)('flood_group', self.channel_name)
